package com.zmn.plat.admin.controller.common.category;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.services.interfaces.category.BaseCategoryService;

/**
 * @author duanzuocai
 * @version v1.0
 * @since 2018/10/24 15:33
 * @类说明：分类级联菜单查询
 */
@Controller
@RequestMapping("/common/categ/")
public class CommonCategoryController extends PlatBaseController {
    @Resource
    BaseCategoryService baseCategoryService;

    /**
     * 分类联动
     *
     * @param request
     * @param response
     * @param parentId
     */
    @RequestMapping(value = "listChilds")
    public void listChilds(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "parentId", defaultValue = "1") int parentId) {
        if (parentId == 0) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }

        List<BaseCategory> items = baseCategoryService.listByParentId(parentId, GlobalDict.STATUS_ENABLE);

        StringBuilder sb = new StringBuilder("[");
        String jsonFormat = "[\"%s\",\"%s\"]%s ";

        for (int i = 0; i < items.size(); i++) {
            BaseCategory item = items.get(i);
            String name = item.getName();
            sb.append(String.format(jsonFormat, items.get(i).getCategId(), name, (i == items.size() - 1 ? "" : ",")));
        }
        sb.append("]");

        ResponseUtil.outWrite(response, sb.toString());
    }

    @RequestMapping(value = "listChildsForShow")
    public void listChildsForShow(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "parentId", defaultValue = "1") int parentId) {
        if (parentId == 0) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }

        List<BaseCategory> items = baseCategoryService.listByParentIdForShow(parentId, GlobalDict.STATUS_ENABLE);

        StringBuilder sb = new StringBuilder("[");
        String jsonFormat = "[\"%s\",\"%s\"]%s ";

        for (int i = 0; i < items.size(); i++) {
            BaseCategory item = items.get(i);
            String name = item.getName();
            sb.append(String.format(jsonFormat, items.get(i).getCategId(), name, (i == items.size() - 1 ? "" : ",")));
        }
        sb.append("]");

        ResponseUtil.outWrite(response, sb.toString());
    }
}
